package com.base.filter;

import com.base.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class AuthFilter extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
        Subject subject = getSubject(servletRequest, servletResponse);
        //这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() 让它同时也兼容remember这种情况
        return subject.isAuthenticated() || subject.isRemembered();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //isAccessAllowed 如果返回false，代表无登录状态，或不是通过记住我功能进来，
        Result result = Result.errorResult(500, "无认证");
        ObjectMapper objectMapper=new ObjectMapper();
        String s = objectMapper.writeValueAsString(result);
        response.getWriter().write(s);
        return false;
    }
}
